package com.jcl.tree.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2021/2/4 23:18
 */
public class TreeBuilder
{
    /**
     * 使用递归方法建树
     *
     * @param
     * @return
     */
    public static <T> List<T> buildTree(List<T> list) throws InvocationTargetException,
            IllegalAccessException, NoSuchMethodException
    {
        List<T> trees = new ArrayList<>();
        for (T treeNode : list)
        {
            Method method = treeNode.getClass().getDeclaredMethod("getParentId", (Class<?>) null);
            Object value = method.invoke(treeNode, (Object) null);
            if ("0".equals(String.valueOf(value)))
            {
                trees.add(findChildren(treeNode, list));
            }
        }
        return trees;
    }

    public static <T> T findChildren(T t, List<T> treeNodes) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException
    {
        Method getIdMethod = t.getClass().getDeclaredMethod("getId");
        String id = String.valueOf(getIdMethod.invoke(t, (Object) null));
        for (T it : treeNodes)
        {
            Method getParentIdMethod = it.getClass().getDeclaredMethod("getParentId");
            Object parentId = getParentIdMethod.invoke(it, (Object) null);
            if (id.equals(String.valueOf(parentId)))
            {
                Method getChildrenMethod = t.getClass().getDeclaredMethod("getChildren");
                Object children = getChildrenMethod.invoke(t, (Object) null);
                if (null == children)
                {
                    Method setChildrenMethod = t.getClass().getDeclaredMethod("setChildren", HashSet.class);
                    setChildrenMethod.invoke(t, new HashSet<T>());
                }
                ((HashSet<T>) getChildrenMethod.invoke(t, null)).add(findChildren(it, treeNodes));
            }
        }
        return t;
    }

    public static void main(String[] args)
    {

    }
}
